﻿using Aspose.Cells.Drawing.Texts;
using Dapper;
using Estsh.Core.Base;
using Estsh.Core.Dapper;
using Estsh.Core.Model.EnumUtil;
using Estsh.Core.Model.Extend;
using Estsh.Core.Model.Extend.Models;
using Estsh.Core.Models;
using Estsh.Core.Repositories;
using Estsh.Core.Wms.IRepositories;
using Microsoft.Extensions.Primitives;
using System.Data;
using System.Text;

namespace Estsh.Core.Wms.Repositories
{
    /// <summary>
    /// 快速入库
    /// </summary>
    public class QuicklyInStockRepository : BaseRepository<BaseEntity>, IQuicklyInStockRepository
    {
        public QuicklyInStockRepository(DapperDbContext _dapperDbContext) : base(_dapperDbContext)
        {

        }
        //根据库位获取库位信息
        public List<SysLocate> GetLocateByName(string locateName)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT a.locate_id,a.locate_name,a.locate_type,a.locate_capacity,b.enum_desc as locate_typeDesc,a.enabled FROM dbo.sys_locate a (nolock) LEFT JOIN sys_enum b (nolock) ON b.enum_type='sys_locate_type' and a.locate_type=b.enum_value "
                                     + "WHERE a.locate_name = '" + locateName + "'");
                List<SysLocate> sysLocates = dbConn.Query<SysLocate>(stringBuilder.ToString()).ToList();
                return sysLocates;
            }
        }

        //根据库位获取条码信息
        public List<SysStock> GetStockQtyByLocate(string locateName)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("  SELECT SUM(qty) as qty FROM dbo.sys_stock (nolock) WHERE locate_name = '" + locateName + "' AND status IN ('50','60','80') and enabled='Y' ");
                List<SysStock> sysStocksLocateCount = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();//库位在库数
                return sysStocksLocateCount;
            }
        }
        //根据分组号分组获取所有零件号
        public List<SysStock> GetStockPartByGroupNo(string groupNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
				// stringBuilder.Append("SELECT a.part_no FROM dbo.sys_stock a (nolock) WHERE group_no = '" + groupNo + "'  and status=40 and a.enabled='Y'  GROUP BY a.part_no ");
				stringBuilder.Append("SELECT a.part_no FROM dbo.sys_stock a (nolock) WHERE carton_type=0 and group_no = '" + groupNo + "'  and status=40 and a.enabled='Y'  GROUP BY a.part_no ");
				List<SysStock> sysstockByGroupNoCount = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
                return sysstockByGroupNoCount;
            }
        }

        //根据条码号获取条码信息
        public List<SysStock> GetStockByCartonNo(string cartonNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT a.*,b.enum_name as stock_status FROM sys_stock a (nolock) left join sys_enum b (nolock) on a.status=b.enum_value and b.enum_type = 'sys_stock_status' WHERE carton_no='" + cartonNo + "'");
                List<SysStock> sysStocksLocateCount = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
                return sysStocksLocateCount;
            }
        }
        //根据库位名称获取库位信息
        public List<SysLocate> GetLocateAndPartByLocate(string locateName)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT * FROM dbo.sys_locate a (nolock) LEFT JOIN sys_locate_part b (nolock) ON a.locate_id = b.locate_id  WHERE a.locate_name = '" + locateName + "' and a.enabled='Y'");
                List<SysLocate> sysLocates = dbConn.Query<SysLocate>(stringBuilder.ToString()).ToList();
                return sysLocates;
            }
        }
        //根据分组号获取条码数量和
        public List<SysStock> GetStockQtyByGroupNo(string groupNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT SUM(qty) as qty FROM dbo.sys_stock (nolock) WHERE group_no = '" + groupNo + "' and status in (40)  and enabled='Y' ");
                List<SysStock> sysStocks = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
                return sysStocks;
            }
        }

        //根据分组号获取条码信息
        public List<SysStock> GetStockByGroupNo(string groupNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
				//stringBuilder.Append("SELECT * FROM dbo.sys_stock (nolock) WHERE carton_type=0 and  group_no = '" + groupNo + "' and status in (40)  and enabled='Y' ");
				stringBuilder.Append("SELECT * FROM dbo.sys_stock (nolock) WHERE carton_type=0 and  group_no = '" + groupNo + "' and status in (40)  and enabled='Y' ");
				List<SysStock> sysStocks = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
                return sysStocks;
            }
        }

		//根据分组号获取条码信息
		public List<SysStock> GetUpdateStockByGroupNo(string groupNo)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append("SELECT * FROM dbo.sys_stock (nolock) WHERE group_no = '" + groupNo + "' and status =40 and enabled='Y' ");
				List<SysStock> sysStocks = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
				return sysStocks;
			}
		}

		public List<SysStock> GetStockInByCartonNo(string cartonNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT part_no,part_spec,sum(qty) qty,locate_name,count(1) carton_qty FROM dbo.sys_stock (nolock) WHERE carton_no = '" + cartonNo + "' and status in (50)  and enabled='Y' group by part_no,part_spec,locate_name ");
                List<SysStock> sysStocks = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
                return sysStocks;
            }
        }

        ////根据分组号获取入库条码信息
        //public List<SysStock> GetStockInByGroupNo(string groupNo)
        //{
        //    using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
        //    {
        //        dbConn.Open();
        //        StringBuilder stringBuilder = new StringBuilder();
        //        stringBuilder.Append("SELECT * FROM dbo.sys_stock WHERE group_no = '" + groupNo + "' and status in (50)  and enabled='Y' ");
        //        List<SysStock> sysStocks = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
        //        return sysStocks;
        //    }
        //}

        //根据分组号获取入库条码信息
        public List<SysStock> GetStockInByGroupNo(string groupNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT part_no,part_spec,sum(qty) qty,locate_name,count(1) carton_qty FROM dbo.sys_stock (nolock) WHERE group_no='" + groupNo + "' and status in (50)  and enabled='Y' group by part_no,part_spec,locate_name");
                List <SysStock> sysStocks = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
                return sysStocks;
            }
        }

        public List<SysStock> GetStockInRefOrderNo(string refOrderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append(" SELECT  * FROM dbo.sys_stock WHERE ref_order_no='"+ refOrderNo + "' ");
                List<SysStock> sysStocks = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
                return sysStocks;
            }
        }

        //根据库位获取在库条码信息
        public List<SysStock> GetStockByLocateName(string locateName)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT * FROM sys_stock (nolock) WHERE locate_name='" + locateName + "' AND status in (50,60,80) AND enabled='Y'");
                List<SysStock> sysStocks = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
                return sysStocks;
            }
        }



		//根据条码号获取条码信息
		public List<SysStock> GetStockByCartonNoN(string cartonNo)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append("SELECT a.*,b.enum_name as stock_status FROM sys_stock a (nolock) left join sys_enum b (nolock) on a.status=b.enum_value and b.enum_type = 'sys_stock_status' WHERE carton_no='" + cartonNo + "'");
				List<SysStock> sysStocksLocateCount = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
				return sysStocksLocateCount;
			}
		}


		public List<SysStock> GetStockByStatusByCartonNo(string cartonNo)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append("SELECT a.* FROM sys_stock a (nolock)  WHERE  a.Status=40 and a.carton_no='" + cartonNo + "'");
				List<SysStock> sysStocksLocateCount = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
				return sysStocksLocateCount;
			}
		}

		/// <summary>
		/// 根据扫描条码，判断是否有上级关系
		/// </summary>
		/// <param name="cartonNo"></param>
		/// <returns></returns>
		public List<WmsRackPackage_Extend> GetWmsRackPackageType(string cartonNo)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append("SELECT  * FROM dbo.wms_rack_package WHERE corton_no='"+ cartonNo + "' AND enabled='Y' ");
				List<WmsRackPackage_Extend> packages = dbConn.Query<WmsRackPackage_Extend>(stringBuilder.ToString()).ToList();
				return packages;
			}
		}



		/// <summary>
		/// 判断是否有扫描的包装条码
		/// </summary>
		/// <param name="cartonNo"></param>
		/// <returns></returns>
		public List<WmsRack_Extend> GetRackTypeN(string cartonNo)
        {
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append("SELECT * FROM dbo.wms_rack WHERE rack_no ='" + cartonNo + "' AND enabled='Y'");
				List <WmsRack_Extend> WmsRackCount = dbConn.Query<WmsRack_Extend>(stringBuilder.ToString()).ToList();
				return WmsRackCount;
			}
		}

		/// <summary>
		/// 根据周转箱条码找出包装条码
		/// </summary>
		/// <param name="cartonNo"></param>
		/// <returns></returns>
		public List<SysStock> GetWmsRackPackageByStock(string cartonNo)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				StringBuilder stringBuilderStock = new StringBuilder();
				stringBuilderStock.Append("SELECT  * FROM dbo.sys_stock WHERE carton_no in ( SELECT  corton_no FROM dbo.wms_rack_package WHERE rack_no='" + cartonNo + "' AND enabled='Y' ) AND enabled='Y' and Status=40 ");
				List<SysStock> stockInfos = dbConn.Query<SysStock>(stringBuilderStock.ToString()).ToList();
				return stockInfos;


			}
		}

		/// <summary>
		/// 根据包装条码找到周转箱
		/// </summary>
		/// <param name="cartonNo"></param>
		/// <returns></returns>
		public List<SysStock> GetWmsByStock(string cartonNo)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				StringBuilder stringBuilderStock = new StringBuilder();
				stringBuilderStock.Append(" SELECT * FROM dbo.sys_stock WHERE carton_no =(SELECT top 1 rack_no FROM dbo.wms_rack_package WHERE corton_no='"+ cartonNo + "' AND enabled='Y' ) AND status=40 AND enabled='Y' ");
				List<SysStock> stockInfos = dbConn.Query<SysStock>(stringBuilderStock.ToString()).ToList();
				return stockInfos;


			}
		}



        /// <summary>
        /// 向下查询
        /// </summary>
        /// <param name="wmsRack"></param>
        public void GetStockByRackListDown(string cartonNo, string factoryId, ref List<SysStock> GetAllStock)
        {

            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                StringBuilder stringBuilderRackPackage = new StringBuilder();
                stringBuilderRackPackage.Append(@"select b.rack_no,b.corton_no as package_carton_on,b.packageType as package_packagetype,a.* from sys_stock as a left join wms_rack_package as b on a.carton_no=b.corton_no 
                where b.rack_no = @cartonNo  and b.enabled = 'Y' and a.enabled = 'Y'");
                // and a.factory_id =@factory_id 
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@cartonNo", cartonNo);
                //parameters.Add("@factory_id", factoryId);

                List<SysStock> WmsRackPackageCount = dbConn.Query<SysStock>(stringBuilderRackPackage.ToString(), parameters).ToList();
                if (WmsRackPackageCount.Count != 0)
                {
                    foreach (var item in WmsRackPackageCount)
                    {
                        GetAllStock.Add(item);
                        GetStockByRackListDown(item.CartonNo, factoryId, ref GetAllStock);
                    }

                }

            }

        }







        List<WmsRackPackage_Extend> WmsRackPackages=new List<WmsRackPackage_Extend>();//定义全局

        /// <summary>
        /// 根据扫描的包装条码，查出所用的箱条码
        /// </summary>
        /// <param name="cartonNo"></param>
        /// <returns></returns>
		public List<WmsRackPackage_Extend> GetStockOrRackList(string cartonNo)
        {

			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				StringBuilder stringBuilderRackPackage = new StringBuilder();
				stringBuilderRackPackage.Append("SELECT * FROM dbo.wms_rack_package WHERE    ='" + cartonNo + "'  and enabled='Y' ");
				List<WmsRackPackage_Extend> WmsRackPackageCount = dbConn.Query<WmsRackPackage_Extend>(stringBuilderRackPackage.ToString()).ToList();

                WmsRackPackages = new List<WmsRackPackage_Extend>();
				foreach (var item in WmsRackPackageCount)
				{
					WmsRackPackages.Add(item);
					GetStockOrRackList2(item);
                    GetStockOrRackList3(item);
				}
				return WmsRackPackages;

			}

		}
        /// <summary>
        /// 向下查询
        /// </summary>
        /// <param name="wmsRack"></param>
		public void GetStockOrRackList2(WmsRackPackage_Extend wmsRack)
		{

			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				StringBuilder stringBuilderRackPackage = new StringBuilder();
				stringBuilderRackPackage.Append("SELECT * FROM dbo.wms_rack_package (nolock) WHERE rack_no ='" + wmsRack.CortonNo + "'  and enabled='Y' ");
				List<WmsRackPackage_Extend> WmsRackPackageCount = dbConn.Query<WmsRackPackage_Extend>(stringBuilderRackPackage.ToString()).ToList();


				if (WmsRackPackageCount.Count !=0 )
				{
					//wmsRack.package_Extends = new List<WmsRackPackage_Extend>();
					//wmsRack.package_Extends.AddRange(WmsRackPackageCount);
					
					foreach (var item in WmsRackPackageCount)
                    {
						WmsRackPackages.Add(item);
						GetStockOrRackList2(item);
					}

				}

			}

		}

        /// <summary>
        /// 向上查询
        /// </summary>
        /// <param name="wmsRack"></param>
		public void GetStockOrRackList3(WmsRackPackage_Extend wmsRack)
		{

			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				StringBuilder stringBuilderRackPackage = new StringBuilder();
				stringBuilderRackPackage.Append("SELECT * FROM dbo.wms_rack_package WHERE corton_no ='" + wmsRack.RackNo + "'  and enabled='Y' ");
				List<WmsRackPackage_Extend> WmsRackPackageCount = dbConn.Query<WmsRackPackage_Extend>(stringBuilderRackPackage.ToString()).ToList();


				if (WmsRackPackageCount.Count != 0)
				{
					//wmsRack.package_Extends = new List<WmsRackPackage_Extend>();
					//wmsRack.package_Extends.AddRange(WmsRackPackageCount);

					foreach (var item in WmsRackPackageCount)
					{
						WmsRackPackages.Add(item);
						GetStockOrRackList3(item);
					}

				}

			}

		}



		/// <summary>
		/// 根据零件号，订单号来查询入库表明细数据
		/// </summary>
		/// <param name="cartonNo"></param>
		/// <param name="partId"></param>
		/// <returns></returns>
		public List<WmsOutstockDetail> GetOutstockDetailList(string cartonNo, string partId)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append(" SELECT item_no,plan_date,plan_time FROM dbo.wms_outstock_detail WHERE order_no='"+ cartonNo + "' AND part_id='"+ partId + "' AND enabled='Y'");
				List<WmsOutstockDetail> outstockDetails  = dbConn.Query<WmsOutstockDetail>(stringBuilder.ToString()).ToList();
				return outstockDetails;
			}
		}


		//事务批量执行添加、修改
		public int SQLTransaction(List<string> sqlStrings, List<DynamicParameters> parameterList)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                if (dbConn.State == ConnectionState.Closed)
                {
                    dbConn.Open();
                }
                //执行事务
                IDbTransaction transaction = dbConn.BeginTransaction();
                if (parameterList == null || parameterList.Count == 0)
                {
                    try
                    {
                        for (int i = 0; i < sqlStrings.Count; i++)
                        {
                            dbConn.Execute(sqlStrings[i], null, transaction);
                        }
                        transaction.Commit();
                        return 1;
                    }
                    catch (Exception exception)
                    {
                        transaction.Rollback();
                        return 0;
                    }
                }
                else
                {
                    try
                    {
                        for (int i = 0; i < sqlStrings.Count; i++)
                        {
                            dbConn.Execute(sqlStrings[i], parameterList[i], transaction);
                        }
                        transaction.Commit();
                        return 1;
                    }
                    catch (Exception exception)
                    {
                        transaction.Rollback();
                        return 0;
                    }
                }
            }
        }
    }
}
